package com.hx.haowumall.haowumallmember.service.impl;

import com.alibaba.fastjson.JSON;
import com.hx.common.utils.HttpUtils;
import com.hx.haowumall.haowumallmember.dao.MemberLevelDao;
import com.hx.haowumall.haowumallmember.entity.MemberLevelEntity;
import com.hx.haowumall.haowumallmember.exception.PhoneExistException;
import com.hx.haowumall.haowumallmember.exception.UsernameExistException;
import com.hx.haowumall.haowumallmember.vo.MemberLoginVo;
import com.hx.haowumall.haowumallmember.vo.MemberRegistVo;
import com.hx.haowumall.haowumallmember.vo.SocialUserVo;
import com.hx.haowumall.haowumallmember.vo.UserInfoVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hx.common.utils.PageUtils;
import com.hx.common.utils.Query;

import com.hx.haowumall.haowumallmember.dao.MemberDao;
import com.hx.haowumall.haowumallmember.entity.MemberEntity;
import com.hx.haowumall.haowumallmember.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = new MemberEntity();

        //设置默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());

        //检查用户名和手机号是否唯一  为了能让controller感知异常 使用异常机制
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUserName());
        //设置用户名
        entity.setUsername(vo.getUserName());
        //设置手机号
        entity.setMobile(vo.getPhone());
        //设置昵称
        entity.setNickname(vo.getUserName());

        //设置密码 密码需要加密存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassWord());
        entity.setPassword(encode);

        //其他默认信息
        entity.setGender(0);
        entity.setCreateTime(new Date());

        memberDao.insert(entity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException{
        MemberDao memberDao = this.baseMapper;
        Integer mobile = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0){
            throw new PhoneExistException();
        }

    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException{
        MemberDao memberDao = this.baseMapper;
        Integer usernameCount = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (usernameCount > 0){
            throw new UsernameExistException();
        }

    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();

        //1、去数据库查询 SELECT * FROM `ums_member` WHERE username=? OR mobile=?
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).
                or().eq("mobile", loginacct));
        if (entity == null){
            //登陆失败
            return null;
        }else {
            //1、从数据库中获取加秘的密码
            String passwordDP = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //2、密码匹配
            boolean matches = passwordEncoder.matches(password, passwordDP);
            if (matches){
                return entity;
            }else {
                return null;
            }
        }

    }

    @Override
    public MemberEntity login(SocialUserVo socialUserVo) throws Exception {


        //gitee需要发多一次请求查到用户id
        HashMap<String, String> acMap = new HashMap<>();
        acMap.put("access_token",socialUserVo.getAccess_token());
        HttpResponse doGet = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<String, String>(), acMap);
        if (doGet.getStatusLine().getStatusCode()== 200){
            String userJson = EntityUtils.toString(doGet.getEntity());
            UserInfoVo userInfoVo = JSON.parseObject(userJson, UserInfoVo.class);
            String uid = userInfoVo.getId();

            //1、判断当前社交用户登录过该系统
            MemberDao memberDao = this.baseMapper;
            MemberEntity entity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));


            if (entity != null) {
                //这个用户已经注册
                MemberEntity update = new MemberEntity();
                update.setId(entity.getId());
                update.setExpiresIn(socialUserVo.getExpires_in());
                update.setAccessToken(socialUserVo.getAccess_token());
                memberDao.updateById(update);

                entity.setAccessToken(socialUserVo.getAccess_token());
                entity.setExpiresIn(socialUserVo.getExpires_in());
                return entity;
            }else {
                //2、没有查到社交用户对应的账号，创建一个
                MemberEntity regist = new MemberEntity();
                //3、查询当前社交用户的账号信息
                regist.setSocialUid(userInfoVo.getId());
                regist.setNickname(userInfoVo.getName());

                regist.setSocialUid(userInfoVo.getId());
                regist.setAccessToken(socialUserVo.getAccess_token());
                regist.setExpiresIn(socialUserVo.getExpires_in());

                this.baseMapper.insert(regist);
                return regist;
            }

        }

       return null;
    }

}